package com.itheima.demo;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;


public class CruDemo {
    private SqlSession session = null;

    @Before
    public void before() throws IOException {
        InputStream is = Resources.getResourceAsStream("sql.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        session = factory.openSession();
    }

    @After
    public void after() {
        session.commit();
        session.close();
    }
    //1.查询全部
    @Test
    public void findAll() {
        List<User> list = session.selectList("one.findAll");
        for (User user : list) {
            System.out.println(user);
        }
    }
    //2.通过id查询
    @Test
    public void findById() {
        User user = session.selectOne("one.findById",2);
        System.out.println(user);
    }
    //3.新增
    @Test
    public void save() {
        User user = new User();
        user.setUsername("张亚");
        user.setPwd("666");
        user.setAge(10086);
        user.setSex(0);
        user.setHobby("嫖娼");
        session.insert("one.saveUser",user);
    }
    //4.更新
    @Test
    public void update() {
        User user = new User();
        user.setId(15);
        user.setUsername("张亚子");
        user.setPwd("8777");
        session.update("one.updateUser",user);
    }
    //5.删除
    @Test
    public void deleteById() {
        session.delete("one.deleteById",12);
    }
    //6.统计数量
    @Test
    public void total() {
        int i = session.selectOne("one.total");
        System.out.println(i);
    }
    //7.占位符模糊查询
    @Test
    public void findLikeName1() {
        List<User> users = session.selectList("one.findLikeName1", "%f%");
        for (User user : users) {
            System.out.println(user);
        }
    }
    //8.字符串拼接模糊查询
    @Test
    public void findLikeName2() {
        List<User> users = session.selectList("one.findLikeName2", "貂");
        for (User user : users) {
            System.out.println(user);
        }
    }
}
